package com.sunwayhorizo.health.business.registries.employee.query;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.seam.annotations.Name;

import com.sunwayhorizo.health.business.dto.ResultsDTO;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.rim.Employee;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.platform.base.BaseManager;

@Name("EmployeeQuery")
@Stateless
public class EmployeeQuery extends BaseManager implements EmployeeQueryLocal
{
    @PersistenceContext(unitName = "sunwayhealth")
    private EntityManager em;


    @SuppressWarnings("unchecked")
    public List<Role> findEmpByDeptIdAndPage(int currentPage, int pageSize, String name, String departmentId) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select emp from Employee emp ");
        String cond = " where 1=1 ";
        if (StrUtil.isNotEmpty(name))
        {
            jbql.append("  left join emp.playerEntities as play left join play.entyNamesList ename");
            cond += " and ename.formatted like '%" + name + "%'";
        }
        if (StrUtil.isNotEmpty(departmentId))
        {
            cond += " and emp.scoperEntities.entityId=" + departmentId;
        }
        Query query = em.createQuery(jbql.toString() + cond);
        ResultsDTO dto = new ResultsDTO();
        if (currentPage == 0)
        {
            currentPage = 1;
        }
        dto.setToPage(currentPage);
        dto.setPageSize(pageSize);
        query.setFirstResult(dto.getBeginIndex());
        query.setMaxResults(dto.getPageSize());
        List<Role> list = query.getResultList();
        return list;
    }


    @SuppressWarnings("unchecked")
    public List<Role> findEmployeeByWorkGroup(int currentPage, int pageSize, String name, String workGroupId) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select emp from Employee emp ");
        String cond = " where 1=1 ";
        if (StrUtil.isNotEmpty(name))
        {
            jbql.append("  LEFT JOIN emp.playerEntities play LEFT JOIN play.entyNamesList ename");
            cond += " and ename.formatted like '%" + name + "%'";
        }
        if (StrUtil.isNotEmpty(workGroupId))
        {
            jbql.append(" LEFT JOIN emp.sourceRoleRimCoreRoleLink link LEFT JOIN link.targetRole tar");
            cond += "  and tar.roleId=?1";
        }
        Query query = em.createQuery(jbql.toString() + cond);
        if (StrUtil.isNotEmpty(workGroupId))
        {
            query.setParameter(1, Long.parseLong(workGroupId));
        }
        ResultsDTO dto = new ResultsDTO();
        if (currentPage == 0)
        {
            currentPage = 1;
        }
        dto.setToPage(currentPage);
        dto.setPageSize(pageSize);
        query.setFirstResult(dto.getBeginIndex());
        query.setMaxResults(dto.getPageSize());
        List<Role> list = query.getResultList();
        return list;
    }


    @SuppressWarnings({ "unchecked" })
    public int findEmployeeCount(String name, String departmentId, String workGroupId) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select count(emp.roleId) from Employee emp ");
        String cond = " where 1=1 ";
        if (StrUtil.isNotEmpty(name))
        {
            jbql.append("  LEFT JOIN emp.playerEntities play LEFT JOIN play.entyNamesList ename");
            cond += " and ename.formatted like '%" + name + "%'";
        }
        if (StrUtil.isNotEmpty(departmentId))
        {
            cond += " and emp.scoperEntities.entityId=" + departmentId;
        }
        if (StrUtil.isNotEmpty(workGroupId))
        {
            jbql.append(" LEFT JOIN emp.sourceRoleRimCoreRoleLink link LEFT JOIN link.targetRole tar");
            cond += "  and tar.roleId=?1";
        }
        Query query = em.createQuery(jbql.toString() + cond);
        if (StrUtil.isNotEmpty(workGroupId))
        {
            query.setParameter(1, Long.parseLong(workGroupId));
        }
        List<Long> list = query.getResultList();
        if (ListUtil.isNotEmpty(list))
        {
            log.info("员工总记录数为" + list.get(0).intValue());
            return list.get(0).intValue();
        }
        return 0;
    }


    @SuppressWarnings("rawtypes")
    public List findEmpByDeptOrDicCode(String departmentId, String dicCode) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append("select emp.roleId,part.literal,ii.extensionTxt from Employee emp ");
        jbql.append(" left join emp.roleIiList ii ");
        jbql.append(" left join  emp.playerEntities play ");
        jbql.append(" left join play.entyNamesList ename left join ename.entyNamePartsList part left join ename.entyNameUsesList users");
        String cond = " where users.use='L' ";
        if (StrUtil.isNotEmpty(dicCode))
        {
            jbql.append(" LEFT JOIN emp.roleCdSetsList rcd");
            cond += " and rcd.conceptCode=?1";
        }
        if (StrUtil.isNotEmpty(departmentId))
        {
            cond += " and emp.scoperEntities.entityId=?2";
        }
        Query query = em.createQuery(jbql.toString() + cond);
        if (StrUtil.isNotEmpty(dicCode))
        {
            query.setParameter(1, dicCode);
        }
        if (StrUtil.isNotEmpty(departmentId))
        {
            query.setParameter(2, Long.parseLong(departmentId));
        }
        List empList = query.getResultList();
        return empList;
    }


    @Override
    public Employee findEmployeeByCode(String empCode)
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append(" select distinct emp from Employee emp left join emp.roleIiList rii ");
        jbql.append(" where rii.extensionTxt= ");
        jbql.append("'");
        jbql.append(empCode);
        jbql.append("'");
        @SuppressWarnings("unchecked")
        List<Employee> list = em.createQuery(jbql.toString()).getResultList();
        if (list.isEmpty())
        {
            log.info("EmployeeQuery-findEmployeeByCode-查询" + empCode + "员工为空!");
            return null;
        }
        else
        {
            return list.get(0);
        }

    }


    @SuppressWarnings("unchecked")
    public List<Role> findEmployeeList(long roleId, String empId, String departmentId) throws Hl7Exception
    {
        log.info("调用的方法是findEmployeeList");

        StringBuilder jbql = new StringBuilder();
        jbql.append(" select emp from Employee emp ");
        String cond = " where 1=1";
        // 判断角色的主键id
        if (roleId > 0)
        {
            cond += " and emp.roleId=?1";
        }
        if (!StrUtil.isEmpty(empId))
        {
            jbql.append("  LEFT JOIN emp.roleIiList rii ");
            cond += " and rii.extensionTxt=?2";
        }
        if (!StrUtil.isEmpty(departmentId))
        {
            cond += " and emp.scoperEntities.entityId=?3";
        }
        Query query = em.createQuery(jbql.toString() + cond);
        if (roleId > 0)
        {
            query.setParameter(1, roleId);
        }
        if (StrUtil.isNotEmpty(empId))
        {
            query.setParameter(2, empId);
        }
        if (StrUtil.isNotEmpty(departmentId))
        {
            query.setParameter(3, Long.valueOf(departmentId));
        }
        List<Role> list = query.getResultList();
        if (ListUtil.isNotEmpty(list))
        {
            log.info("查询出" + list.size() + "个员工角色");
        }
        return list;
    }


    @SuppressWarnings("rawtypes")
    public List findEmployeeByWGId(String workGroupId, String dicCode) throws Hl7Exception
    {
        StringBuilder jbql = new StringBuilder();
        jbql.append("select emp.roleId,epart.literal from Employee emp LEFT JOIN  emp.playerEntities play LEFT JOIN play.entyNamesList ename ");
        jbql.append(" LEFT JOIN ename.entyNamePartsList epart LEFT JOIN ename.entyNameUsesList euser ");
        String cond = " where euser.use='L' ";
        if (StrUtil.isNotEmpty(dicCode))
        {
            jbql.append(" LEFT JOIN emp.roleCdSetsList rcd");
            StringBuilder newdicCode = new StringBuilder();
            if (dicCode.contains("-"))
            {
                String[] str = dicCode.split("-");
                newdicCode.append("(");
                newdicCode.append("" + Long.parseLong(str[0]) + "");
                newdicCode.append("," + Long.parseLong(str[1]) + "");
                newdicCode.append(")");
                cond += " and (rcd.conceptCode=" + Long.parseLong(str[0]) + " or rcd.conceptCode=" + Long.parseLong(str[1]) + ")";
            }
            else
                cond += " and rcd.conceptCode='" + dicCode + "'";
        }
        if (StrUtil.isNotEmpty(workGroupId))
        {
            jbql.append(" LEFT JOIN emp.sourceRoleRimCoreRoleLink link LEFT JOIN link.targetRole tar");
            cond += "  and tar.roleId=?1";
        }
        Query query = em.createQuery(jbql.toString() + cond);
        if (StrUtil.isNotEmpty(workGroupId))
        {
            query.setParameter(1, Long.parseLong(workGroupId));
        }
        List list = query.getResultList();
        if (ListUtil.isNotEmpty(list))
        {
            return list;
        }
        return null;
    }


    public List<Employee> validateExsit(String employId) throws Hl7Exception
    {
        StringBuilder jpql = new StringBuilder();
        jpql.append("select emp from Employee emp left join emp.roleIiList ii where ii.extensionTxt='");
        jpql.append(employId);
        @SuppressWarnings("unchecked")
        List<Employee> employees = em.createQuery(jpql.toString()).getResultList();
        return employees;
    }

}
